package com.example.nowcodercommunity.controller.intercepter;

import com.example.nowcodercommunity.entity.LoginTicket;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.service.UserService;
import com.example.nowcodercommunity.util.CookieUtil;
import com.example.nowcodercommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 登录票据拦截器
 * 处理用户登录后的信息存储和持有部分
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求中获取Ticket串
        String ticket = CookieUtil.getValue(request,"ticket");

        // 若存在该串，通过该串查询数据库中是否存在对应Ticket对象
        if(ticket!=null){
            LoginTicket loginTicket = userService.findTicketByTicket(ticket);
            // 验证是否存在，若存在，验证是否过期
            if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())){
                // 通过工具类持有该用户信息与线程中
                User user = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 于Controller处理后，模版处理前，将该对象获取并加入Model对象，以便网页获取
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 模版渲染后，清除服务器中的数据，释放空间
        hostHolder.clean();
    }
}
